package com.skydroid.demo.ui.activity

import android.content.Context
import android.content.Intent
import android.media.MediaPlayer
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import com.skydroid.demo.R
import com.skydroid.demo.databinding.ActivityMediaPlayerTestBinding

class MediaPlayerTestActivity:AppCompatActivity(),SurfaceHolder.Callback {

    private var mBind: ActivityMediaPlayerTestBinding? = null

    private var player: MediaPlayer? = null

    private var sh: SurfaceHolder? = null

    private var sfv: SurfaceView? = null

    private var stream_url =
        "rtsp://192.168.0.10:8554/H264Video"
//        "rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mov"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBind = DataBindingUtil.setContentView(this,
            R.layout.activity_media_player_test
        )
        sfv = mBind?.bigScreen
        player = MediaPlayer()
        player?.setDataSource(this, Uri.parse(stream_url))
        sh = sfv?.getHolder()
        sh?.addCallback(this)

        mBind?.btnPlayer?.setOnClickListener {
            play()
        }
    }

    companion object{
        fun start(context: Context){
            context.startActivity(Intent(context,
                MediaPlayerTestActivity::class.java))
        }
    }

    private fun play(){
       if ( player?.isPlaying == true){
           return
       }
        mBind?.progressBar?.visibility = View.VISIBLE
        player?.setOnPreparedListener(MediaPlayer.OnPreparedListener {
            Log.e("MediaPlayerTestActivity","setOnPreparedListener")
            mBind?.progressBar?.visibility = View.GONE
            player?.start()
            player?.setLooping(true)
        })
        Thread{
            player?.prepare()
        }.start()



    }

    override fun surfaceChanged(holder: SurfaceHolder?, format: Int, width: Int, height: Int) {
        player?.setDisplay(holder)
        Log.e("MediaPlayerTestActivity","surfaceChanged")
    }

    override fun surfaceDestroyed(holder: SurfaceHolder?) {
        Log.e("MediaPlayerTestActivity","surfaceDestroyed")
    }

    override fun surfaceCreated(holder: SurfaceHolder?) {
        Log.e("MediaPlayerTestActivity","surfaceCreated")
    }

    override fun onDestroy() {
        super.onDestroy()
        player?.stop()
        player = null
    }
}